<template>
  <el-dialog
    title="还欠款"
    width="1080px"
    :visible="value"
    @close="handleClose"
  >
    <el-form inline>
      <el-form-item label="开单TC">{{ data.yiyaBillingMain.tc }}</el-form-item>
    </el-form>
    <el-table
      stripe
      border
      show-summary
      :summary-method="getSummaries"
      :data="data.yiyaItemBillingExtends"
    >
      <el-table-column
        label="项目名称"
        align="center"
        min-width="150"
        prop="itemName"
      ></el-table-column>
      <el-table-column
        label="项目应收（元）"
        align="center"
        min-width="100"
        prop="receivablePrice"
      ></el-table-column>
      <el-table-column
        label="项目已收（元）"
        align="center"
        min-width="150"
        prop="payAmount"
      ></el-table-column>
      <el-table-column
        label="本次交费（元）"
        align="center"
        min-width="150"
        prop="thisPay"
      ></el-table-column>
      <el-table-column
        label="项目欠款（元）"
        align="center"
        min-width="150"
        prop="preOwingPrice"
      ></el-table-column>
    </el-table>
    <el-card class="mt20" shadow="never">
      <el-form inline>
        <el-form-item label="本次补缴" style="margin-bottom: 0">
          {{ data.total.thisPay }}
        </el-form-item>
        <el-form-item label="剩余欠费" style="margin-bottom: 0">
          <span style="color: red">{{ data.total.preOwingPrice }}</span>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="mt20" :body-style="{ paddingBottom: 0 }">
      <el-form>
        <el-form-item
          v-for="(item, index) in modeAndMonies"
          :key="item.closingMode + index"
          label="支付方式"
        >
          <template>
            <el-input
              :value="item.closingMoney"
              style="width: 250px"
              placeholder="请输入内容"
              @input="handleInput($event, item)"
              @blur="handleBlur(item)"
            >
              <el-select
                slot="prepend"
                v-model="item.closingMode"
                style="width: 100px"
                placeholder="请选择"
              >
                <el-option
                  v-for="option in paymentMode"
                  :key="option.dictSort"
                  :label="option.dictLabel"
                  :value="option.dictLabel"
                >
                </el-option>
              </el-select>
            </el-input>
            <el-button
              v-if="index === 0"
              style="margin-left: 10px"
              type="primary"
              icon="el-icon-plus"
              circle
              @click="handleAdd"
            ></el-button>
            <el-button
              v-else
              style="margin-left: 10px"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(index)"
            ></el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="mt20" shadow="never" :body-style="{ paddingBottom: 0 }">
      <el-form inline>
        <el-form-item label="备注">
          <el-input
            v-model="remarks"
            style="width: 500px"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="请输入内容"
          >
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <template slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        :disabled="thisPay !== data.total.thisPay"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { sendPayment } from '@/api/services/entries'
import { paymentMethodOptions } from '@/utils/options'
import { paymentMethodEnum } from '@/utils/enums'

export default {
  name: 'Repayment',
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({
        yiyaBillingMain: {},
        total: {},
      }),
    },
  },
  data() {
    return {
      loading: false,
      modeAndMonies: [],
      remarks: '',
    }
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
    }),
    ...mapGetters('dict', ['paymentMode']),
    paymentMethodOptions() {
      return paymentMethodOptions
    },
    thisPay() {
      return this.modeAndMonies
        .reduce((total, { closingMoney }) => total + +closingMoney, 0)
        .toFixed(2)
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
      }
    },
  },
  methods: {
    init() {
      this.modeAndMonies = []
      this.pushPaymentMethod()
    },
    pushPaymentMethod() {
      this.modeAndMonies.push({
        closingMode: paymentMethodEnum['现金'],
        closingMoney: (+this.data.total.thisPay - +this.thisPay).toFixed(2),
      })
    },
    handleClose() {
      this.$emit('close', false)
    },
    getSummaries({ columns }) {
      return columns.map(({ label, property }) =>
        label === '项目名称' ? '合计' : this.data.total[property] || ''
      )
    },
    handleInput(e, item) {
      if (isNaN(+e)) {
        return
      }
      item.closingMoney = e
    },
    handleBlur(item) {
      const amount = +item.closingMoney
      const thisPay = +this.thisPay - +item.closingMoney
      const cur = thisPay + amount
      if (cur > +this.data.total.thisPay) {
        item.closingMoney = (+this.data.total.thisPay - thisPay).toFixed(2)
        return
      }
      item.closingMoney = amount.toFixed(2)
    },
    handleAdd() {
      if (this.thisPay === this.data.total.thisPay) {
        return
      }
      this.pushPaymentMethod()
    },
    handleDelete(index) {
      if (this.modeAndMonies.length <= 1) {
        return
      }
      const [{ closingMoney }] = this.modeAndMonies.splice(index, 1)
      const paymentMethod = this.modeAndMonies[index - 1]
      paymentMethod.closingMoney = (
        +paymentMethod.closingMoney + +closingMoney
      ).toFixed(2)
    },
    async handleSubmit() {
      await this.$confirm('是否确认此操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      try {
        this.loading = true
        const { id: billingMainId, clinicPersonId } = this.data.yiyaBillingMain
        const { id: mainClosingEntriesId } = this.data.yiyaMainClosingEntries
        const { petCardAmount } = this.data.total
        const modeAndMonies = [...this.modeAndMonies]
        if (petCardAmount !== '0.00') {
          modeAndMonies.push({
            closingMode: '储值划扣',
            closingMoney: petCardAmount,
          })
        }
        await sendPayment({
          billingMainId,
          clinicPersonId,
          mainClosingEntriesId,
          modeAndMonies,
          charge: this.userName,
          closingRemarks: this.remarks,
          return: false,
        })
        this.handleClose()
        this.msgSuccess('缴费成功')
        this.$emit('ok')
      } finally {
        this.loading = false
      }
    },
  },
}
</script>
